﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Quartz.Net.Factory;
using Quartz.Net.Model;
using Newtonsoft.Json;
using System.Text;
using System.Web;
using System.Configuration;
using System.IO;

namespace Quartz.Net.WebApi.Controllers
{
    [RoutePrefix("api/JobInfo")]
    public class JobInfoController : ApiController
    {
        /// <summary>
        /// 获取任务信息
        /// </summary>
        /// <param name="cl"></param>
        /// <returns></returns>
        [Route("InfoManger")]
        [HttpPost]
        public HttpResponseMessage InfoManger(InfoModel cl)
        {
            int pageSize = int.Parse(cl.pageSize);
            int pageNumber = int.Parse(cl.pageNumber);
            //string 
            resultJsonModel res = new resultJsonModel();
            try
            {
                List<Task_Quartz_JobtriggerRunModel> list = factoryClass.GetJobRun().OrderByDescending(m => Convert.ToInt16(m.XH)).ToList();
                res.code = 200;
                res.rows = list.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
                res.total = list.Count;
            }
            catch (Exception ex)
            {
                res.code = 500;
                res.msg = "获取任务失败";
                factoryClass.InsertRrrorlog(ex.Message, "", LogsStatus.Error);
            }

            factoryClass.InsertOperation("", OperateStatus.Select, cl.OPERATETOR, cl.OPERATETORNAME, "", "查询数据");

            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(res), Encoding.GetEncoding("UTF-8"), "text/plain") };
            return result;
        }
        /// <summary>
        /// 获取单个运行任务信息
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [Route("GetOneInfo")]
        [HttpGet]
        public resultJsonModel GetOneInfo(string id, string OPERATETOR, string OPERATETORNAME)
        {
            resultJsonModel result = new resultJsonModel();
            try
            {
                List<Task_Quartz_JobTriggerModel> model = factoryClass.JobTriggerGetInfo().Where(m => m.VALID == "1" && m.NGUID == id).ToList();
                result.rows = model;
                result.code = 200;

                string path = model[0].JOBPATH;
                DirectoryInfo root = new DirectoryInfo(path);
                FileInfo[] files = root.GetFiles();
                //List<string> list = new List<string>();
                List<object> list = new List<object>();

                for (int i = 0; i < files.Length; i++)
                {
                    list.Add(new { id = files[i].Name, name = HttpUtility.UrlEncode(files[i].DirectoryName + "\\" + files[i].Name) });
                }
                result.data = list;

            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "获取信息失败！";
                factoryClass.InsertRrrorlog(ex.Message, "获取信息失败！", LogsStatus.Error);
            }
            factoryClass.InsertOperation(id, OperateStatus.Select, OPERATETOR, OPERATETORNAME, "", "查询单个数据");
            return result;
        }
        /// <summary>
        /// 更改任务信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [Route("UpdateJobInfo")]
        [HttpPost]
        public resultJsonModel UpdateJobInfo([FromBody]string value)
        {
            resultJsonModel result = new resultJsonModel();

            Task_Quartz_JobTriggerModel model = new Task_Quartz_JobTriggerModel();
            try
            {
                HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
                HttpRequestBase request = context.Request;//定义传统request对象            
                string JOBSNAME = request.Form["JOBSNAME"];
                string NGUID = request.Form["NGUID"];
                string JOBJJ = request.Form["JOBJJ"];
                string JOBCRON = request.Form["JOBCRON"];
                model.JOBSNAME = Convert.ToString(JOBSNAME);
                model.NGUID = Convert.ToString(NGUID);
                model.JOBJJ = Convert.ToString(JOBJJ);
                model.JOBCRON = Convert.ToString(JOBCRON);
                model.ISCHANGE = "1";
                factoryClass.UpdateJobInfo(model);
                result.code = 200;
                factoryClass.InsertOperation(model.NGUID, OperateStatus.Update, request.Form["OPERATETOR"], request.Form["OPERATETORNAME"], "", "更改任务信息");
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "更新任务信息失败";
                factoryClass.InsertRrrorlog(ex.Message, "更新任务信息失败", LogsStatus.Error);
            }

            return result;
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [Route("UpdateJobValid")]
        [HttpGet]
        public resultJsonModel UpdateJobValid(string NGUID, string OPERATETOR, string OPERATETORNAME)
        {
            resultJsonModel result = new resultJsonModel();
            Task_Quartz_JobTriggerModel model = new Task_Quartz_JobTriggerModel();
            try
            {
                model.NGUID = NGUID;
                model.VALID = "0";
                factoryClass.UpdateJobValid(model);
                result.code = 200;
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "删除任务信息失败";
                factoryClass.InsertRrrorlog(ex.Message, "删除任务信息失败", LogsStatus.Error);
            }
            factoryClass.InsertOperation(NGUID, OperateStatus.Delete, OPERATETOR, OPERATETORNAME, "", "删除任务信息");
            return result;
        }

        /// <summary>
        /// 更改运行状态信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [Route("UpdateISChange")]
        [HttpPost]
        public resultJsonModel UpdateISChange(dynamic info)
        {
            resultJsonModel result = new resultJsonModel();
            try
            {
                string NGUID = Convert.ToString(info.NGUID);
                string change = Convert.ToString(info.runStatus);
                factoryClass.InsertOperation(NGUID, OperateStatus.Select, Convert.ToString(info.OPERATETOR), Convert.ToString(info.OPERATETORNAME), "", "执行一次");
                factoryClass.UpdateISChange(NGUID, change);
                result.code = 200;
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "启动任务失败";
                factoryClass.InsertRrrorlog(ex.Message, "启动任务失败", LogsStatus.Error);
            }

            return result;
        }

        /// <summary>
        /// 更改运行状态信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [Route("UpdateRunStatus")]
        [HttpPost]
        public resultJsonModel UpdateRunStatus(dynamic info)
        {
            resultJsonModel result = new resultJsonModel();

            try
            {

                string[] NGUID = Convert.ToString(info.NGUID).Split('^');
                for (int i = 0; i < NGUID.Length; i++)
                {
                    string runStatus = Convert.ToString(info.runStatus);
                    RunStatus run = RunStatus.Suspend;
                    if (runStatus == "1")//运行
                    {
                        run = RunStatus.Run;
                    }
                    else if (runStatus == "3")//暂停
                    {
                        run = RunStatus.Suspend;
                    }
                    else if (runStatus == "2")
                    {
                        run = RunStatus.Wait;//等待下一次运行
                    }

                    factoryClass.InsertOperation(NGUID[i], OperateStatus.Select, Convert.ToString(info.OPERATETOR), Convert.ToString(info.OPERATETORNAME), "", run.ToString() + "-更改运行状态信息");
                    factoryClass.UpdateRunStatus(NGUID[i], run);
                }

                result.code = 200;
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "更改运行状态信息失败";
                factoryClass.InsertRrrorlog(ex.Message, "更改运行状态信息失败", LogsStatus.Error);
            }

            return result;
        }
        /// <summary>
        /// 验证程序执行时间表达式是否正确
        /// </summary>
        /// <param name="cron"></param>
        /// <returns></returns>
        [Route("CheckCron")]
        [HttpPost]
        public resultJsonModel CheckCron(dynamic info)
        {
            resultJsonModel result = new resultJsonModel();

            if (factoryClass.ValidExpression(Convert.ToString(info.cron)))
            {
                result.code = 200;
            }
            else
            {
                result.code = 500;
                result.msg = "输入的执行程序时间不正确！";
            }
            return result;
        }

        /// <summary>
        /// 插入job信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("InsertJob")]
        [HttpPost]
        public resultJsonModel InsertJob([FromBody]string value)
        {
            resultJsonModel result = new resultJsonModel();
            Task_Quartz_JobTriggerModel model = new Task_Quartz_JobTriggerModel();
            try
            {
                HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
                string TaskPath = ConfigurationManager.AppSettings["TaskPath"].ToString();
                HttpRequestBase request = context.Request;//定义传统request对象            
                string JOBSNAME = request.Form["JOBSNAME"];
                string JOBJJ = request.Form["JOBJJ"];
                string JOBCRON = request.Form["JOBCRON"];
                model.JOBSNAME = Convert.ToString(JOBSNAME);
                model.JOBJJ = Convert.ToString(JOBJJ);
                model.JOBCRON = Convert.ToString(JOBCRON);

                HttpFileCollectionBase filelist = request.Files;
                String Tpath = "/job" + factoryClass.MaxXh() + "/";
                string FilePath = TaskPath + "\\" + Tpath + "\\";
                string filename = string.Empty;
                if (filelist != null && filelist.Count > 0)
                {
                    DirectoryInfo di = new DirectoryInfo(FilePath);
                    if (!di.Exists) { di.Create(); } else { DeleteDir(FilePath); }

                    for (int i = 0; i < filelist.Count; i++)
                    {
                        HttpPostedFileBase file = filelist[i];
                        filename = file.FileName;
                        //string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        try
                        {
                            file.SaveAs(FilePath + filename);
                        }
                        catch (Exception ex)
                        {
                            //result = "上传文件写入失败：" + ex.Message;
                            factoryClass.InsertRrrorlog(ex.Message, "上传文件写入失败", LogsStatus.Error);
                        }
                    }
                }
                else
                {
                    //result = "上传的文件信息不存在！";
                }
                factoryClass.InsertOperation("", OperateStatus.Select, request.Form["OPERATETOR"], request.Form["OPERATETORNAME"], "", "新增任务");
                int n = factoryClass.InsertJob(model);
                if (n <= 0)
                {
                    result.code = 500;
                    result.msg = "新增失败！";
                }
                else
                {
                    result.code = 200;
                }
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "新增失败";
                factoryClass.InsertRrrorlog(ex.Message, "新增失败", LogsStatus.Error);
            }

            return result;



        }

        [Route("DeleteFile")]
        [HttpGet]
        public resultJsonModel DeleteFile(string filePath, string OPERATETOR, string OPERATETORNAME)
        {
            resultJsonModel result = new resultJsonModel();
            string path = HttpUtility.UrlDecode(filePath);

            try
            {
                factoryClass.InsertOperation("", OperateStatus.Select, OPERATETOR, OPERATETORNAME, "", "删除附件===" + path);
                if (File.Exists(path))
                {
                    File.Delete(path);
                    result.code = 200;
                }
                else
                {
                    result.code = 500;
                    result.msg = "未获取到该文件!";
                }
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "删除文件失败！";
                factoryClass.InsertRrrorlog(ex.Message, "删除文件失败！", LogsStatus.Error);
            }


            return result;
        }

        [Route("GetCron")]
        [HttpGet]
        public resultJsonModel GetCron(string cron)
        {
            resultJsonModel result = new resultJsonModel();
            try
            {
                if (factoryClass.ValidExpression(cron))
                {
                    List<string> list = factoryClass.GetNextFireTime(cron, 5);
                    result.code = 200;
                    result.data = list;
                }
                else
                {
                    result.code = 500;
                    result.msg = "不是正确的表达式！";
                }
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "获取失败！";
            }


            return result;

        }

        [Route("ValidExpression")]
        [HttpGet]
        public resultJsonModel ValidExpression(string cron)
        {
            resultJsonModel result = new resultJsonModel();
            try
            {
                if (factoryClass.ValidExpression(cron))
                {

                    result.code = 200;
                }
                else
                {
                    result.code = 500;
                    result.msg = "不是正确的表达式！";
                }
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.msg = "获取失败！";
            }


            return result;

        }
        private static void DeleteDir(string file)
        {
            try
            {
                //去除文件夹和子文件的只读属性
                //去除文件夹的只读属性
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

                //去除文件的只读属性
                System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);

                //判断文件夹是否还存在
                if (Directory.Exists(file))
                {
                    foreach (string f in Directory.GetFileSystemEntries(file))
                    {
                        if (File.Exists(f))
                        {
                            //如果有子文件删除文件
                            File.Delete(f);
                            //Console.WriteLine(f);
                        }
                        else
                        {
                            //循环递归删除子文件夹
                            DeleteDir(f);
                        }
                    }

                    //删除空文件夹
                    Directory.Delete(file);
                    //Console.WriteLine(file);
                }

            }
            catch (Exception ex) // 异常处理
            {
                //Console.WriteLine(ex.Message.ToString());// 异常信息
                factoryClass.InsertRrrorlog(ex.Message, "删除文件夹", LogsStatus.Error);
            }
        }



    }

}
